<template>
  <!-- <video v-if="!isVideoError" ref="videoRef" class="video-item" @click="handleClick">
    <source :src="src" />
  </video> -->
  <video v-show="!isVideoError" ref="videoRef" class="video-item" @click="handleClick"></video>
  <div v-if="isVideoError" class="placeholder-box">
    <slot name="placeholder">
      <n-empty :description="src ? '加载失败' : '暂无视频'" />
    </slot>
  </div>
  <n-modal v-model:show="showViewModal" :show-icon="false" preset="dialog" style="width: 1200px">
    <div class="modal-view-box">
      <video class="video" controls>
        <source :src="src" />
      </video>
    </div>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';

defineOptions({
  name: 'ViewVideo'
});
const props = withDefaults(
  defineProps<{
    src: string;
  }>(),
  {
    src: ''
  }
);

const videoRef = ref<HTMLVideoElement | null>(null);
const isVideoError = ref<boolean>(false);
const showViewModal = ref<boolean>(false);

onMounted(() => {
  videoRef.value?.addEventListener('error', handleVideoError);
  //src本应直接绑定到source元素上，但如果先绑定的话无法监听到error事件
  videoRef.value?.setAttribute('src', props.src);
});

onUnmounted(() => {
  videoRef.value?.removeEventListener('error', handleVideoError);
});

watch(
  () => props.src,
  (val) => {
    isVideoError.value = false;
    videoRef.value?.setAttribute('src', val);
  }
);

function handleVideoError() {
  isVideoError.value = true;
}

function handleClick() {
  showViewModal.value = true;
}
</script>

<style lang="scss" scoped>
.video-item {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
}
.placeholder-box {
  margin: auto;
}
.modal-view-box {
  height: 80vh;
  .video {
    width: 100%;
    height: 100%;
  }
}
</style>
